package com.zjuh.goodboy.biz.dal.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.zjuh.goodboy.biz.dal.daointerface.UserDAO;
import com.zjuh.goodboy.biz.dal.dataobject.UserDO;

public class JdbcUserDAO extends JdbcDaoSupport implements UserDAO {

	private static final String fullColumns = "id, nick, email, password, last_login, gmt_create, gmt_modifed";
	
	@Override
	public long create(UserDO userDO) {
		String sql = "insert into goodboy_user (nick, email, password, last_login, gmt_create, gmt_modifed) values (?, ?, ?, ?, now(), now())";
		this.getJdbcTemplate().update(sql, new Object[] {userDO.getNick(), userDO.getEmail(), userDO.getPassword(), userDO.getLastLogin()} );
		return getJdbcTemplate().queryForLong("select last_insert_id()");
		
	}

	@Override
	public UserDO queryByEmail(String email) {
		String sql = "select " + fullColumns + " from goodboy_user where email = ?";
		return (UserDO)this.getJdbcTemplate().queryForObject(sql, new Object[] { email }, new RowMapper() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				return rs2UserDO(rs);
			}
			
		});
	}
	
	private UserDO rs2UserDO(ResultSet rs) throws SQLException {
		UserDO user = new UserDO();
		user.setId(rs.getLong("id"));
		user.setNick(rs.getString("email"));
		user.setPassword(rs.getString("password"));
		user.setLastLogin(rs.getTimestamp("last_login"));
		user.setGmtCreate(rs.getTimestamp("gmt_create"));
		user.setGmtModified(rs.getTimestamp("gmt_modifed"));
		return user;
	}

	@Override
	public UserDO queryById(long id) {
		String sql = "select " + fullColumns + " from goodboy_user where id = ?";
		return (UserDO)this.getJdbcTemplate().queryForObject(sql, new Object[] { id }, new RowMapper() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				return rs2UserDO(rs);
			}
			
		});
	}

	@Override
	public UserDO queryByNick(String nick) {
		String sql = "select " + fullColumns + " from goodboy_user where nick = ?";
		return (UserDO)this.getJdbcTemplate().queryForObject(sql, new Object[] { nick }, new RowMapper() {

			@Override
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				return rs2UserDO(rs);
			}
			
		});
	}

	
	
}
